// 服务层
const adminController = require("../controller/adminController")
// 导入自定义错误
const {ParameterError, ValidationError} = require("../utils/customError")
const md5 = require("md5");
const {validateFunc} = require("../utils/tools");
const userController = require("../controller/userController");

// 检查查询对象是否为空 如果为空则抛出错误
exports.loginAdmin = async (loginInfo) => {
    if (!loginInfo) {
        throw new ParameterError("参数错误")
    }

    if (!loginInfo.loginId) {
        throw new ParameterError("请输入登录账号")
    }

    if (!loginInfo.loginPwd) {
        throw new ParameterError("请输入登录密码")
    }

    loginInfo.loginPwd = md5(loginInfo.loginPwd)


    return adminController.findAdmin(loginInfo)
}


// 注册用户
exports.registerAdmin = async (adminInfo) => {
    const userRule = {
        loginId: {
            presence: {
                // 是否为空
                allowEmpty: false
            },
            type: "string"
        },
        loginPwd: {
            presence: {
                // 是否为空
                allowEmpty: false
            },
            type: "string"
        },
        nickname: {
            presence: {
                // 是否为空
                allowEmpty: false
            },
            type: "string"
        },
    }

    const result = adminInfo.loginId && await adminController.findAdmin({loginId:adminInfo.loginId});
    if (result) {
        // 通过验证后需要验证用户名是否已经存在
        throw new ValidationError("用户名已存在")
    }
    try {
        await validateFunc(userRule, adminInfo);
        // 密码需要MD5加密
        adminInfo.loginPwd = md5(adminInfo.loginPwd)
        const res = await adminController.createAdmin(adminInfo);
        res.loginPwd = "null"
        return res
    } catch (e) {
        throw new ValidationError("数据验证失败")
    }
}

// 修改用户信息
exports.editAdminInfo = async (id, newAdminInfo) => {
    if (newAdminInfo.loginId) {
        const result = await adminController.findAdmin({loginId:newAdminInfo.loginId})
        const resp = await adminController.findAdmin({
            _id:id,
            loginId:newAdminInfo.loginId
        })
        if (result && !resp) {
            throw new ValidationError("用户名已存在")
        }
    }
   if(newAdminInfo.newLoginPwd){
       newAdminInfo.loginPwd = md5(newAdminInfo.newLoginPwd)
       const result = await adminController.findAdmin({
           _id:id,
           loginPwd:md5(newAdminInfo.oldLoginPwd)
       })

       if(!result){
           throw new ValidationError("旧密码错误")
       }
   }

    return adminController.updateAdmin(id, newAdminInfo)
}


// 判断用户名是否存在
exports.getIsLoginById = (loginId)=>{
    return adminController.findAdmin({loginId})
}
